package com.example.project.Controller;

import com.example.project.Entity.Comment;
import com.example.project.Service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class CommentController {

    @Autowired
    private CommentService commentService;

    @PostMapping("/commentBlog")
    public Map<String, Object> CommentBlog(@RequestBody Map<String, String> co_map){
        String user_id = co_map.get("user_id");
        String blog_id = co_map.get("blog_id");
        String content = co_map.get("content");
        Map<String, Object> map = new HashMap<>();
        try{
            Comment comment1 = new Comment(user_id, blog_id, content);
            commentService.saveComment(comment1);
            map.put("errno", "1");
            map.put("message", "评论博文成功！");
        } catch (Exception e) {
            map.put("errno", "11001");
            map.put("message", "评论博文失败！");
        }
        return map;
    }

    @PostMapping("/deleteComment")
    public Map<String, Object> DeleteComment(@RequestBody Map<String, String> de_map){
        int comment_id = Integer.parseInt(de_map.get("comment_id"));
        int blog_id = Integer.parseInt(de_map.get("blog_id"));
        Map<String, Object> map = new HashMap<>();
        try{
            commentService.deleteComment(comment_id, blog_id);
            map.put("errno", "1");
            map.put("message", "删除博文成功！");
        } catch (Exception e) {
            map.put("errno", "12001");
            map.put("message", "删除博文失败！");
        }
        return map;
    }

    @PostMapping("/showComment")
    public Map<String, Object> showComment(@RequestBody Map<String, String> sh_map){
        int blog_id = Integer.parseInt(sh_map.get("blog_id"));
        Map<String, Object> map = new HashMap<>();
        try{
            List<Comment> c_list = commentService.selectCommentByBlog(blog_id);
            if(c_list.isEmpty()){
                map.put("errno", "13001");
                map.put("message", "该博文暂无评论！");
            }  else {
                map.put("errno", "1");
                map.put("message", "获取评论成功！");
                map.put("result", c_list);
            }
        } catch (Exception e){
            map.put("errno", "13002");
            map.put("message", "获取评论失败！");
        }
        return map;
    }
}
